package com.hps.shoping.good.service.impl;

import com.hps.shoping.good.entitys.Good;
import com.hps.shoping.good.entitys.OrderMessage;
import com.hps.shoping.good.mapper.GoodMapper;
import com.hps.shoping.good.mapper.OrderMessageMapper;
import com.hps.shoping.good.service.GoodService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author heps
 * @date 2019/9/1 9:45
 */
@Service
public class GoodServiceImpl implements GoodService {

    private final GoodMapper goodMapper;

    private final OrderMessageMapper orderMessageMapper;

    public GoodServiceImpl(GoodMapper goodMapper, OrderMessageMapper orderMessageMapper) {
        this.goodMapper = goodMapper;
        this.orderMessageMapper = orderMessageMapper;
    }

    @Override
    public List<Good> findAll() {
        return goodMapper.selectAll();
    }

    @Override
    @Transactional
    public boolean updateStock(String orderId, long goodId) {
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setCreatedTime(new Date());
        orderMessage.setOrderId(orderId);
        orderMessage.setStatus(false);

        int insert = 0;
        try {
            insert = orderMessageMapper.insert(orderMessage);
        } catch (Exception e) {
            Example example = new Example(OrderMessage.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId", orderId);
            List<OrderMessage> orderMessages = orderMessageMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(orderMessages)) {
                return orderMessages.get(0).getStatus();
            }
        }
        if (insert > 0) {
            int i = goodMapper.updateStock(goodId);
            orderMessage.setStatus(i > 0);
            orderMessageMapper.updateByPrimaryKey(orderMessage);
            return i > 0;
        }
        return false;
    }
}
